package org.jeecg.modules.sggg.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sggg.entity.SgLowDoseCt;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgTumor;
import org.jeecg.modules.sggg.service.ISgLowDoseCtService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgTumorService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 低剂量螺旋CT
 * @Author: jeecg-boot
 * @Date: 2023-06-26
 * @Version: V1.0
 */
@Api(tags = "低剂量螺旋CT")
@RestController
@RequestMapping("/sggg/LDCT")
@Slf4j
public class SgLowDoseCtController extends JeecgController<SgLowDoseCt, ISgLowDoseCtService> {
    @Autowired
    private ISgLowDoseCtService sgLowDoseCtService;
    @Autowired
    private ISgMemberService sgMemberService;
    @Autowired
    private ISgTumorService sgTumorService;

    /**
     * 分页列表查询
     *
     * @param sgLowDoseCt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "低剂量螺旋CT-分页列表查询")
    @ApiOperation(value = "低剂量螺旋CT-分页列表查询", notes = "低剂量螺旋CT-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgLowDoseCt>> queryPageList(SgLowDoseCt sgLowDoseCt,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<SgLowDoseCt> queryWrapper = QueryGenerator.initQueryWrapper(sgLowDoseCt, req.getParameterMap());
        Page<SgLowDoseCt> page = new Page<SgLowDoseCt>(pageNo, pageSize);
        IPage<SgLowDoseCt> pageList = sgLowDoseCtService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sgLowDoseCt
     * @return
     */
    @AutoLog(value = "低剂量螺旋CT-添加")
    @ApiOperation(value = "低剂量螺旋CT-添加", notes = "低剂量螺旋CT-添加")
    //@RequiresPermissions("org.jeecg.modules:sg_low_dose_ct:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgLowDoseCt sgLowDoseCt) {
        sgLowDoseCtService.save(sgLowDoseCt);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgLowDoseCt
     * @return
     */
    @AutoLog(value = "低剂量螺旋CT-编辑")
    @ApiOperation(value = "低剂量螺旋CT-编辑", notes = "低剂量螺旋CT-编辑")
    //@RequiresPermissions("org.jeecg.modules:sg_low_dose_ct:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgLowDoseCt sgLowDoseCt) {
        sgLowDoseCtService.updateById(sgLowDoseCt);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "低剂量螺旋CT-通过id删除")
    @ApiOperation(value = "低剂量螺旋CT-通过id删除", notes = "低剂量螺旋CT-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:sg_low_dose_ct:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        sgLowDoseCtService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "低剂量螺旋CT-批量删除")
    @ApiOperation(value = "低剂量螺旋CT-批量删除", notes = "低剂量螺旋CT-批量删除")
    //@RequiresPermissions("org.jeecg.modules:sg_low_dose_ct:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sgLowDoseCtService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "低剂量螺旋CT-通过id查询")
    @ApiOperation(value = "低剂量螺旋CT-通过id查询", notes = "低剂量螺旋CT-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgLowDoseCt> queryById(@RequestParam(name = "id", required = true) String id) {
        SgLowDoseCt sgLowDoseCt = sgLowDoseCtService.getById(id);
        if (sgLowDoseCt == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgLowDoseCt);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgLowDoseCt
     */
    //@RequiresPermissions("org.jeecg.modules:sg_low_dose_ct:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgLowDoseCt sgLowDoseCt) {
        return super.exportXls(request, sgLowDoseCt, SgLowDoseCt.class, "低剂量螺旋CT");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("sg_low_dose_ct:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgLowDoseCt.class);
    }


    /**
     * 保存记录
     *
     */
    @PostMapping("/saveLDCT")
    public Result<String> saveLDCT(@RequestParam(required = false) String tumorId,@RequestParam String memberId, @RequestBody JSONObject CTData) {
        if (sgLowDoseCtService.count(new QueryWrapper<SgLowDoseCt>().eq("ct_no", CTData.getString("ctNo"))) > 0) {
            return Result.error("CT号已存在！");
        }
//		 保存数据
        SgLowDoseCt ldct = new SgLowDoseCt();
        ldct.setMemberId(memberId);
        ldct.setCtNo(CTData.getString("ctNo"));
        ldct.setCtDate(new Date(CTData.getLong("ctDate")));
        ldct.setFollowIs(CTData.getInteger("followIs"));
        ldct.setFollowNum(CTData.getString("followNum"));
        ldct.setFollowState(CTData.getString("followState"));
        ldct.setAirFlueState(CTData.getString("airFlueState"));
        ldct.setRemark(CTData.getString("remark"));
        JSONArray noduleArray = CTData.getJSONArray("data");
//        是否进行保存了 如果没有下方进行判断
        boolean isSave=false;
        for (int i = 0; i < noduleArray.size(); i++) {
            JSONObject tempData = noduleArray.getJSONObject(i);
            //如果tempData里面什么都不包含[空的结节 那么不进行保存]
            if (tempData.size() == 0) {
                continue;
            }
            ldct.setId(String.valueOf(new Date().getTime()) + (Math.random() * 1000 + 100));
            ldct.setNodulePlace(tempData.getString("nodulePlace"));
            ldct.setNoduleLesion(tempData.getString("noduleLesion"));
            ldct.setNoduleEdge(tempData.getString("noduleEdge"));
            ldct.setNoduleDensity(tempData.getString("noduleDensity"));
            ldct.setNoduleLong(tempData.getString("noduleLong"));
            ldct.setNoduleShort(tempData.getString("noduleShort"));
            sgLowDoseCtService.save(ldct);
            isSave=true;
        }
//        如果到最后循环结束了都没进行保存 那么说明没有结节 直接保存数据
        if(!isSave){
            sgLowDoseCtService.save(ldct);
        }
//        如果传入了调查记录的id 那么需要给调查记录添加ctNo
        if(StringUtils.isNotEmpty(tumorId)){
            SgTumor tumor=new SgTumor();
            tumor.setId(tumorId);
            tumor.setLdctNo(CTData.getString("ctNo"));
            sgTumorService.updateById(tumor);
        }
        return Result.OK("保存成功！");
    }

    /**
     * 根据ctno查询数据
     */
    @GetMapping("/queryByCtNo")
    public Result<HashMap<String,Object>> queryByCtNo(@RequestParam String ctno){
        HashMap<String,Object> result=new HashMap<>();
        QueryWrapper<SgLowDoseCt> sgqw=new QueryWrapper<>();
        sgqw.eq("ct_no",ctno);
        //根据ct号获取信息
        List<SgLowDoseCt> ldcts=sgLowDoseCtService.list(sgqw);
        if(ldcts.size()<1){
            return Result.error("请求失败,无CT号对应信息！");
        }
        //根据ct号信息中的memberId查询member的信息
        SgMember member=sgMemberService.getById(ldcts.get(0).getMemberId());
        JSONArray datas=new JSONArray();
        datas.addAll(ldcts);
        result.put("member",member);
        result.put("data",datas);
        return Result.OK(result);
    }
}
